﻿using System;
using System.Text;
using System.Web.Mvc;

namespace Solution
{
    public class StandardJsonResult : ActionResult, IStandardResult
    {
        #region 构造

        public StandardJsonResult()
        {
            this.ContentType = "application/json";
            this.State = 1;
        }

        #endregion 构造

        #region 公共属性

        public string Message
        {
            get; set;
        }

        public int State
        {
            get; set;
        }

        #endregion 公共属性

        #region 私有属性

        private string ContentType
        {
            get; set;
        }

        #endregion 私有属性

        #region 公共方法

        /// <summary>
        /// 设置响应头等信息
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = this.ContentType;
            response.ContentEncoding = Encoding.UTF8;
            response.Write(Serializer.ToJson(this.ToJsonObject()));
        }

        public void Fail()
        {
            this.State = 1;
        }

        public void Fail(string message)
        {
            this.State = 1;
            this.Message = message;
        }

        public void Succeed()
        {
            this.State = 0;
        }

        public void Succeed(string message)
        {
            this.State = 0;
            this.Message = message;
        }

        public void Try(Action action)
        {
            try
            {
                action();
                this.Succeed();
            }
            catch (ShowException ex)
            {
                this.Fail(ex.Message);
            }
            catch (Exception ex)
            {
                this.Fail(ExceptionExtension.GetAllMessages(ex));
            }
        }

        #endregion 公共方法

        #region 保护方法

        protected virtual IStandardResult ToJsonObject()
        {
            var result = new StandardResult();
            result.State = this.State;
            result.Message = this.Message;
            return result;
        }

        #endregion 保护方法
    }

    public class StandardJsonResult<T> : StandardJsonResult, IStandardResult<T>
    {
        #region 公共属性

        public T Value
        {
            get; set;
        }

        #endregion 公共属性

        #region 保护方法

        protected override IStandardResult ToJsonObject()
        {
            var result = new StandardResult<T>();
            result.State = this.State;
            result.Message = this.Message;
            result.Value = this.Value;
            return result;
        }

        #endregion 保护方法
    }
}